import random

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

# from .models import ServiceHost
# from .cpu import get_server_status
import json


class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
    #    room_name = 'chat_all_data'
    def websocket_connect(self, message):
        print("有人进行连接了。。。。")
        kefuid=1001
        #获取参数
        self.group_name = self.scope['url_route']['kwargs']['group']
        #判断用户还是客服
        if self.group_name.find('user')>=0:
            room = self.group_name+str(kefuid)
            #如果是用户，用userid+kefuid建立房间号，并且当前用户发送到客服房间号
            async_to_sync(self.channel_layer.group_add)(room, self.channel_name)
            # async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)(
                str(kefuid),  # 房间组名
                {
                    'type': 'send_to_chrom',  # 消费者中处理的函数
                    'data': {"id":self.group_name,"name":"用户"+str(self.group_name)}
                }
            )
        else:
            #如果是客服，用kefuid建立房间号，并且当前客服发送到用户房间号
            async_to_sync(self.channel_layer.group_add)(str(kefuid), self.channel_name)
        # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
        self.accept()

    def websocket_receive(self, message):
        kefuid=1001
        mess = json.loads(message['text'])
        userid = mess['to']
        room = userid+str(kefuid)
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            room,#房间组名
            {
                'type':'send_to_chrom', #消费者中处理的函数
                'data':{"mes":mess['mes']}
            }
        )

        # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
        # 消息持久化 mysql  redis
        # print(message['text'])

    #     data = json.loads(message['text'])
    #     message = data['message']
    #     room = str(data['from'])
    # #    self.send(message)
    #     channel_layer = get_channel_layer()

    #     async_to_sync(channel_layer.group_send)(
    #         room,#房间组名
    #         {
    #             'type':'send_to_chrome', #消费者中处理的函数
    #             'data':message
    #         }
    #     )

    def websocket_disconnect(self, message):
        # 客户端向服务端断开连接时，自动触发
        print("连接断开！！")
        self.group_name = self.scope['url_route']['kwargs']['group']

        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )
        raise StopConsumer()

    # 自定义的处理房间组内的数据
    def send_to_chrom(self, event):
        try:
            data = event.get('data')
            # 接收房间组广播数据，将数据发送给websocket
            self.send(json.dumps(data, ensure_ascii=False))
        except Exception as e:
            pass


# #服务器测试
# class ServerMonitorConsumer(WebsocketConsumer):
#     def connect(self):
#         self.group_name = "monitor"
#         async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
#         self.accept()
#         print("WebSocket 连接成功")
#
#     def disconnect(self, close_code):
#         async_to_sync(self.channel_layer.group_discard)(self.group_name, self.channel_name)
#
#     def receive(self, text_data):
#         print("Received data:", text_data)  # 确认接收到客户端的数据
#
#         # 解析 JSON 数据
#         try:
#             data = json.loads(text_data)
#             print("Parsed data:", data)
#         except json.JSONDecodeError as e:
#             print(f"JSON decode error: {e}")
#             self.send(text_data=json.dumps({"error": "Invalid JSON"}))
#             return
#
#         # 获取所有服务器
#         hosts = ServiceHost.objects.all()
#         print(f"Found {len(hosts)} hosts")
#
#         results = []
#         for host in hosts:
#             print(f"Checking host: {host.name}")
#
#             # 获取 CPU 使用率
#             cpu_usage = get_server_status(
#                 hostname=host.ip,
#                 port=host.port,
#                 username=host.username,
#                 password=host.password,
#                 command="top -bn1 | grep 'Cpu(s)' | awk '{print $2}'"
#             )
#             print(f"CPU usage for {host.name}: {cpu_usage}",1111111111111111111)
#
#             # 随机生成温度
#             temp = round(random.uniform(30.0, 80.0), 2)
#             print(f"Simulated Temperature for {host.name}: {temp}")
#
#             # 判断温度是否超过 60°C
#             if temp > 60.0:
#                 warning = f"警告：服务器 {host.name} 温度过高（{temp}°C）！"
#                 print(warning)
#             else:
#                 warning = ""
#
#             # 组装结果
#             results.append({
#                 "id": host.id,
#                 "name": host.name,
#                 "cpu_usage": cpu_usage,
#                 "temperature": temp,
#                 "warning": warning
#             })
#
#         # 将结果发送回客户端
#         async_to_sync(self.channel_layer.group_send)(
#             self.group_name,
#             {
#                 'type': 'send_status',
#                 'data': results
#             }
#         )
#
#     def send_status(self, event):
#         self.send(text_data=json.dumps(event['data']))
